// wind_speed_monitor/frontend/js/api.js

// API基础URL
const API_BASE_URL = 'http://127.0.0.1:5000/api';
let socket = null;
let eventHandlers = {};

// API通信模块
const api = {
    // 获取所有站点信息
    getStations: async function() {
        try {
            const response = await fetch(`${API_BASE_URL}/stations`);
            const data = await response.json();
            return data.success ? data.stations : {};
        } catch (error) {
            console.error('获取站点信息失败:', error);
            return {};
        }
    },
    
    // 获取特定站点信息
    getStation: async function(stationId) {
        try {
            const response = await fetch(`${API_BASE_URL}/stations/${stationId}`);
            const data = await response.json();
            return data.success ? data.station : null;
        } catch (error) {
            console.error(`获取站点${stationId}信息失败:`, error);
            return null;
        }
    },
    
    // 获取站点历史数据
    getStationData: async function(stationId, hours = 24) {
        try {
            const response = await fetch(`${API_BASE_URL}/stations/${stationId}/data?hours=${hours}`);
            const data = await response.json();
            return data.success ? data.data : [];
        } catch (error) {
            console.error(`获取站点${stationId}数据失败:`, error);
            return [];
        }
    },
    
    // 获取多站点比较数据
    getComparisonData: async function(stationIds, hours = 24) {
        try {
            const response = await fetch(`${API_BASE_URL}/comparison?stations=${stationIds.join(',')}&hours=${hours}`);
            const data = await response.json();
            return data.success ? data.data : {};
        } catch (error) {
            console.error('获取比较数据失败:', error);
            return {};
        }
    },
    
    // 设置风速阈值
    setThreshold: async function(threshold) {
        try {
            const response = await fetch(`${API_BASE_URL}/thresholds`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ threshold })
            });
            const data = await response.json();
            return data.success ? data.threshold : null;
        } catch (error) {
            console.error('设置阈值失败:', error);
            return null;
        }
    },
    
    // 获取当前阈值
    getThreshold: async function() {
        try {
            const response = await fetch(`${API_BASE_URL}/thresholds`);
            const data = await response.json();
            return data.success ? data.threshold : 12.0;
        } catch (error) {
            console.error('获取阈值失败:', error);
            return 12.0;
        }
    },
    
    // 导出数据
    exportData: function(stationId, format = 'csv', hours = 168) {
        // 使用window.open直接下载文件
        window.open(`${API_BASE_URL}/export/${stationId}?format=${format}&hours=${hours}`);
    },
    
    // 初始化WebSocket连接
    initWebSocket: function() {
        if (socket) {
            // 如果已有连接，先关闭
            this.closeWebSocket();
        }
        
        try {
            socket = io('http://127.0.0.1:5000');
            
            socket.on('connect', () => {
                console.log('WebSocket已连接');
                if (eventHandlers.onConnect) eventHandlers.onConnect();
            });
            
            socket.on('disconnect', () => {
                console.log('WebSocket已断开');
                if (eventHandlers.onDisconnect) eventHandlers.onDisconnect();
                
                // 断开连接后尝试重连
                setTimeout(() => {
                    if (!socket || !socket.connected) {
                        this.initWebSocket();
                    }
                }, 5000);
            });
            
            // 接收数据更新
            socket.on('data_update', (data) => {
                console.log('接收到数据更新:', data);
                if (eventHandlers.onDataUpdate) eventHandlers.onDataUpdate(data);
                
                // 触发自定义事件，方便其他模块监听
                const event = new CustomEvent('wind_data_update', { detail: data });
                document.dispatchEvent(event);
            });
            
            // 接收警报
            socket.on('alert', (alert) => {
                console.log('接收到警报:', alert);
                if (eventHandlers.onAlert) eventHandlers.onAlert(alert);
                
                // 触发自定义事件，方便其他模块监听
                const event = new CustomEvent('wind_alert', { detail: alert });
                document.dispatchEvent(event);
            });
            
            // 使全局可访问
            window.windSocket = socket;
            
            return socket;
        } catch (error) {
            console.error('WebSocket连接失败:', error);
            return null;
        }
    },
    
    // 检查WebSocket连接状态
    isSocketConnected: function() {
        return socket && socket.connected;
    },
    
    // 注册事件处理器
    on: function(event, handler) {
        eventHandlers[event] = handler;
        
        // 如果已有socket连接，直接添加监听
        if (socket) {
            if (event === 'onDataUpdate') {
                socket.on('data_update', handler);
            } else if (event === 'onAlert') {
                socket.on('alert', handler);
            } else if (event === 'onConnect') {
                socket.on('connect', handler);
            } else if (event === 'onDisconnect') {
                socket.on('disconnect', handler);
            }
        }
    },
    
    // 取消事件处理器
    off: function(event) {
        if (eventHandlers[event]) {
            delete eventHandlers[event];
        }
        
        // 如果已有socket连接，移除监听
        if (socket) {
            if (event === 'onDataUpdate') {
                socket.off('data_update');
            } else if (event === 'onAlert') {
                socket.off('alert');
            } else if (event === 'onConnect') {
                socket.off('connect');
            } else if (event === 'onDisconnect') {
                socket.off('disconnect');
            }
        }
    },
    
    // 关闭WebSocket连接
    closeWebSocket: function() {
        if (socket) {
            socket.disconnect();
            socket = null;
        }
    },
    
    // 发送自定义消息到服务器（如果需要）
    sendMessage: function(event, data) {
        if (socket && socket.connected) {
            socket.emit(event, data);
            return true;
        }
        return false;
    },
    
    // 批量获取多个站点的数据
    getBatchStationData: async function(stationIds, hours = 24) {
        try {
            const results = {};
            const promises = stationIds.map(stationId => 
                this.getStationData(stationId, hours)
                    .then(data => {
                        results[stationId] = data;
                    })
            );
            
            await Promise.all(promises);
            return results;
        } catch (error) {
            console.error('批量获取站点数据失败:', error);
            return {};
        }
    },
    
    // 使用Mock数据（API不可用时）
    generateMockData: function(stationId, hours = 24) {
        const data = [];
        const now = new Date();
        
        let baseWind = 8;
        if (stationId === 'B') baseWind = 6;
        else if (stationId === 'C') baseWind = 10;
        else if (stationId === 'D') baseWind = 7;
        
        for (let i = hours; i >= 0; i--) {
            const timestamp = new Date(now.getTime() - i * 3600000);
            data.push({
                timestamp: timestamp.toISOString(),
                windSpeed: baseWind + Math.random() * 4 - 2,
                temperature: 20 + Math.random() * 10 - 5,
                humidity: 65 + Math.random() * 30 - 15
            });
        }
        
        return data;
    },
    
    // 获取站点数据（首先尝试API，失败时使用Mock数据）
    getStationDataWithFallback: async function(stationId, hours = 24) {
        try {
            const data = await this.getStationData(stationId, hours);
            if (data && data.length > 0) {
                return data;
            } else {
                console.log(`API返回空数据，使用模拟数据替代站点${stationId}`);
                return this.generateMockData(stationId, hours);
            }
        } catch (error) {
            console.error(`获取站点${stationId}数据失败，使用模拟数据:`, error);
            return this.generateMockData(stationId, hours);
        }
    },
    
    // 检查API可用性
    checkApiAvailability: async function() {
        try {
            const response = await fetch(`${API_BASE_URL}/stations`);
            const data = await response.json();
            return data.success;
        } catch (error) {
            console.error('API不可用:', error);
            return false;
        }
    }
};

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 自动初始化WebSocket连接
    api.initWebSocket();
    
    // 导出全局API对象
    window.windApi = api;
});

// 导出API对象
window.api = api;